from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
import json
import time


#  ChromeDriver 路径,下载地址：https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions-with-downloads.json
chrome_driver_path = "D:/Program Files/chromedriver-win64/chromedriver.exe"

# 设置 Chrome 选项
chrome_options = Options()
# chrome_options.add_argument("--headless")  # 无头模式，不打开浏览器界面
chrome_options.add_argument("--headless=old")  # 无头模式，不打开浏览器界面
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--remote-debugging-port=9222")  # 远程调试端口
chrome_options.add_argument("--disable-web-security")  # 禁用 Web 安全性
chrome_options.add_argument("--ignore-certificate-errors")  # 忽略 SSL 错误

# 启用性能日志记录
chrome_options.set_capability("goog:loggingPrefs", {"performance": "ALL"})

# 启动 Chrome 浏览器
service = Service(chrome_driver_path)
driver = webdriver.Chrome(service=service, options=chrome_options)


class WebMimicUtil:
    def __init__(self, timeout=20):
        self.timeout = timeout

    def get_all_cookies(self, url):
        try:
            # 清空所有 cookies
            driver.delete_all_cookies()

            # 打开目标 URL
            driver.get(url)

            # 显式等待页面加载完成
            WebDriverWait(driver, self.timeout).until(
                EC.presence_of_element_located((By.TAG_NAME, "body"))
            )

            # driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

            time.sleep(5)
            all_cookies = driver.get_cookies()

        except Exception as e:
            print(f"An error occurred: {e}")
        finally:
            # 关闭浏览器
            driver.quit()

        return all_cookies
